package com.linkturing.swing;

import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class LinkLabel extends JLabel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String text, url;

	private boolean isSupported;

	public LinkLabel(String text, String url) {
		this.text = text;

		this.url = url;

		try {
			this.isSupported = Desktop.isDesktopSupported()

					&& Desktop.getDesktop().isSupported(Desktop.Action.BROWSE);

		} catch (Exception e) {
			this.isSupported = false;

		}

		setText(false);

		addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				setText(isSupported);

				if (isSupported){
					setCursor(new Cursor(Cursor.HAND_CURSOR));
				}

			}

			@Override
			public void mouseExited(MouseEvent e) {
				setText(false);

			}

			@Override
			public void mouseClicked(MouseEvent e) {
				try {
					Desktop.getDesktop().browse(

							new java.net.URI(LinkLabel.this.url));

				} catch (Exception ex) {
				}

			}

		});

	}

	private void setText(boolean b) {
		if (!b){
			setText("" + text);
		}
		else{
			setText("" + text);
		}
	}

	public static void main(String[] args) {
		JFrame jf = new JFrame("一个超链接实现的例子-志文工作室");

		JPanel jp = new JPanel();

		jp.add(new LinkLabel("志文工作室", "http://lzw.me"));

		jf.setContentPane(jp);

		jf.pack();

		jf.setVisible(true);

	}
}
